import axios from 'axios';
// eslint-disable-next-line
import store from '@/store';
// eslint-disable-next-line
import router from '@/router';
// eslint-disable-next-line
import { Message } from 'element-ui';
import qs from 'qs';

const request = axios.create({
  // timeout: 2000
  // baseURL:
  // headers:
});

function redirectLogin() {
  router.push({
    name: 'Login',
    query: {
      redirect: router.currentRoute.fullPath,
    },
  });
}

// 获取接口baseURL
function getBaseURL(url) {
  let baseURL = '';
  if (url.startsWith('/boss')) {
    baseURL = 'http://eduboss.lagounews.com';
  } else {
    baseURL = 'http://edufront.lagounews.com';
  }
  return baseURL;
}

// 请求拦截器
request.interceptors.request.use((config) => {
  // 判断 config.url 的前缀，来进行请求 baseURL 的设置
  const nconfig = config;
  nconfig.baseURL = getBaseURL(config.url);
  if (store.state.user) {
    nconfig.headers = { Authorization: store.state.user.access_token };
  }
  return nconfig;
});

// 添加响应拦截器
request.interceptors.response.use(
  (response) => response,
  (error) => {
  // 对响应错误做点什么
    if (error.response) {
      const { status } = error.response;
      if (status === 401) {
        if (!store.state.user) {
          redirectLogin();
        } else {
          Message.error('用户登录信息失效');
          request({
            method: 'POST',
            url: '/front/user/refresh_token',
            data: qs.stringify({
              refreshtoken: store.state.user.refresh_token,
            }),
          }).then((res) => {
            if (res.data.state === 1) {
              store.commit('setUser', res.data.content);
              console.log('token updated!');
            }
            console.log('token update failed');
            store.commit('setUser', null);
            redirectLogin();
            return Promise.reject(error);
          }).then(() => {
            request(error.config);
          }).catch();
        }
      } else if (status === 403) {
        Message.error('没有权限，请联系管理员');
      } else if (status === 404) {
        Message.error('请求资源不存在');
      } else if (status >= 500) {
        Message.error('服务端错误，请联系管理员');
      } else {
        Message.error('未知错误，请联系管理员');
      }
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    return Promise.reject(error);
  },
);

export default request;
